package com.tuanzi.loan.business.repository.templateConf.impl;

import com.tuanzi.loan.business.repository.templateConf.custom.TemplateItemRepositoryCustom;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import com.tuanzi.loan.vo.request.templateConf.TemplateItemRequest;
import com.tuanzi.loan.vo.response.templateConf.TemplateItemResponse;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;

import static com.tuanzi.loan.generated.jooq.loan.tables.LoanApiModelItembasis.LOAN_API_MODEL_ITEMBASIS;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanApiModelProject.LOAN_API_MODEL_PROJECT;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanApiModelType.LOAN_API_MODEL_TYPE;

@SuppressWarnings({"rawtypes"})
@Repository
public class TemplateItemRepositoryImpl extends JOOQBaseRepositoryPlus implements TemplateItemRepositoryCustom {
    @Override
    public Page<TemplateItemResponse> list(TemplateItemRequest searchRequest, Pageable pageable) {
        fields(LOAN_API_MODEL_ITEMBASIS.ID, LOAN_API_MODEL_TYPE.TYPE_NAME,
                LOAN_API_MODEL_PROJECT.TITLE.as("projectName"), LOAN_API_MODEL_ITEMBASIS.TITLE,
                LOAN_API_MODEL_ITEMBASIS.DATA_KEY, LOAN_API_MODEL_ITEMBASIS.CREATE_TIME,
                LOAN_API_MODEL_ITEMBASIS.UPDATE_TIME);
        leftJoin(LOAN_API_MODEL_TYPE, LOAN_API_MODEL_TYPE.ID.eq(LOAN_API_MODEL_ITEMBASIS.TYPE_ID));
        leftJoin(LOAN_API_MODEL_PROJECT, LOAN_API_MODEL_PROJECT.ID.eq(LOAN_API_MODEL_ITEMBASIS.PROJECT_ID));
        eq(LOAN_API_MODEL_ITEMBASIS.ID, searchRequest.getId());
        contains(LOAN_API_MODEL_ITEMBASIS.TITLE, searchRequest.getTitle());
        orderBy(LOAN_API_MODEL_ITEMBASIS.CREATE_TIME, Sort.Direction.DESC);
        return search(pageable, record -> {

            TemplateItemResponse response = new TemplateItemResponse();
            response.setId(record.get(LOAN_API_MODEL_ITEMBASIS.ID));
            response.setTypeName(record.get(LOAN_API_MODEL_TYPE.TYPE_NAME));
            response.setProjectName(record.get(LOAN_API_MODEL_PROJECT.TITLE.as("projectName")));
            response.setTitle(record.get(LOAN_API_MODEL_ITEMBASIS.TITLE));
            response.setDataKey(record.get(LOAN_API_MODEL_ITEMBASIS.DATA_KEY));
            response.setCreateTime(record.get(LOAN_API_MODEL_ITEMBASIS.CREATE_TIME));
            return response;
        });
    }

    @Override
    public void delete(Integer id) {
        dslContext.delete(LOAN_API_MODEL_ITEMBASIS).where(LOAN_API_MODEL_ITEMBASIS.ID.eq(id.longValue())).execute();
    }

    @Override
    protected TableImpl getTable() {
        return LOAN_API_MODEL_ITEMBASIS;
    }
}
